package com.icesoft.core.web.helper.excel;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

/**
 * @author XHH
 *
 */
class CellRead {
	private Map<String, Map<String, String>> mapList = new LinkedHashMap<>();
	private Map<String, String> heads = new LinkedHashMap<>();

	public synchronized void handle(String data, int sheet, int row, int column) {
		String headKey = sheet + "," + column;
		if (row == 0) {
			if (data != null && !"".equals(data.trim())) {
				heads.put(headKey, data);
			}
		} else {
			String head = heads.get(headKey);
			if (head == null) {
				return;
			}
			String dataKey = sheet + "," + row;
			Map<String, String> map = mapList.get(dataKey);
			if (map == null) {
				map = new LinkedHashMap<>();
				for (String title : heads.values()) {
					map.put(title, "");
				}
				mapList.put(dataKey, map);
			}
			if (data != null) {
				map.put(head, data.trim());
			}
		}
	}

	public Collection<Map<String, String>> getDataMap() {
		return mapList.values().stream().filter(CellRead::isNotEmptyMap).collect(Collectors.toList());
	}

	private static boolean isNotEmptyMap(Map<String, String> model) {
		for (Map.Entry<String, String> entry : model.entrySet()) {
			if (StringUtils.isNotBlank(entry.getValue())) {
				return true;
			}
		}
		return false;
	}
}
